package Work;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import moodish.comm.ServerSideMessage;


/***
 * 
 * @author tiago_000
 *	This class take cares of connections made in the server
 */
public class Connections extends Thread {
	ObjectInputStream input;
	ObjectOutputStream output;
	Socket socket;

	private String nickname = null;
	private ServerSide serverSide;

	/***
	 * 
	 * @param socket
	 * @param serverSide
	 * 
	 * This is the constructor Connections it will initialize a input strem
	 * and output stream by a given socket
	 * 
	 * 
	 */
	public Connections(Socket socket, ServerSide serverSide) {
		this.socket = socket;
		this.serverSide = serverSide;
		try {
			input = new ObjectInputStream(this.socket.getInputStream());

			output = new ObjectOutputStream(this.socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
/***
 * 
 * @return nickname
 */
	public String getNickname() {
		return nickname;
	}
/***
 * method that will be reading objects 
 */
	public void run() {

		ToSerialize inComing = null;

		try {
			while (true) {
				inComing = (ToSerialize) input.readObject();
				addTolist(inComing);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/***
	 * 
	 * Add to the list an new message.
	 * 
	 * @params inComing
	 */
	public void addTolist(ToSerialize inComing) {
		ServerMessage sm = (ServerMessage) inComing.getObject();
		if (sm.getType() == ServerSideMessage.Type.CLIENT_CONNECTED) {
			this.nickname = sm.getClientNickname();
		}
		serverSide.addMessage(sm);
	}
/***
 * This method is used to send through the output channel a serialized message;
 */
	public void send(ToSerialize msgSerialized) {
		try {
			output.writeObject(msgSerialized);
			output.reset();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	public void disconnect() {
		try {
			this.interrupt();
			input.close();
			output.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}